<?php

namespace App\Jobs;

use App\Store\Models\Goods\GoodsStockin;
use App\Store\Models\Goods\GoodsStockinInfolist;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Services\Goods\Goods;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockinAuditCancelJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    /**
     * 入库审核
     */
    const QUEUE_JOB = 'stockin-audit-cancel-job';
    public $tries = 3;

    public $initdata = [];

    public $accountinfo = [];
    public $jobId = '';


    public function __construct($data, $accountinfo)
    {

        $this->initdata = $data;
        $this->accountinfo = $accountinfo;
        $this->onQueue(self::QUEUE_JOB);

    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {

        set_time_limit(0);
        ini_set('memory_limit', -1);

        $this->jobId = $this->job->getJobId();

        Log::info('任务ID'.$this->jobId);

        $store_id = $this->initdata['store_id'];
        $list = $this->initdata['list'];
        $id = $this->initdata['id'];
        $cp_id = $this->accountinfo['cp_id'] ?? 0;

        Log::info('审核数据', $list);
        Log::info('账号信息', $this->accountinfo);
        if (empty($data)) {
            Log::info('暂无数据');
        }

        $goods_sn = array_column($list, 'goods_sn_code');

        DB::beginTransaction();
        try {
            GoodsStockList::query()
                ->where(['cp_id' => $cp_id, 'store_id' => $store_id])
                ->whereIn('goods_sn_code', $goods_sn)
                ->update(['is_del' => 2, 'del_at' => time()]);
            foreach ($list as $info) {
                if ($info['audit_status'] == 2) {
                    //审核成功
                    (new  Goods())->addGoodLogs($this->accountinfo, 0, intval($info['store_id']), $info, intval($info['count']), 5, $info['order_sncode']);
                }
                GoodsStockinInfolist::query()
                    ->where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $store_id, 'id' => $info['id']])
                    ->update([
                        'audit_success_count' => 0,
                        'audit_failed_count' => 0,
                        'audit_status' => 1,
                        'audit_at' => time()
                    ]);
            }
            GoodsStockin::query()
                ->where(['cp_id' => $cp_id, 'store_id' => $store_id])
                ->where('id', $id)
                ->update(['audit_success_count' => 0, 'audit_failed_count' => 0, 'audit_status' => 1]);
            DB::commit();
        } catch (\Exception $e) {
            Log::info('入库商品撤销失败' . $e->getLine() . $e->getMessage());
            $this->handleFailure($e);
            DB::rollBack();

        }
    }


    protected function handleFailure(\Throwable $e)
    {
        // 参数错误立即失败，不重试
        if ($e instanceof \InvalidArgumentException) {
            $this->failed($e);
            return;
        }

        // 可重试错误：达到最大尝试次数后标记失败
        if ($e instanceof \RuntimeException) {
            if ($this->attempts() >= $this->tries) {
                $this->failed($e);
            } else {
                throw $e;
            }
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info($exception->getMessage());
    }
}
